import ModalCard from '@/components/ModalCard';
import services from '@/services/demo';
import { removeById } from '@/services/demo/ActivityController';
import { dateFormat } from '@/utils/format';
import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Divider, Drawer, message } from 'antd';
import React, { useRef, useState } from 'react';

const { queryList, remove, modify } =
  services.ActivityController;

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: API.ActivityType) => {
  const hide = message.loading('正在修改');
  try {
    await modify(
      {
        rId: fields.rId || '',
      }
    );
    hide();

    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.ActivityType[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
//  console.log(selectedRows.map(item => item.rId))
  try {
    await remove({
      ids: selectedRows.map(item => item.rId)
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

function HomePage() {
  const [updateModalVisible, handleUpdateModalVisible] =
    useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState<API.ActivityType | {}>({});
  const actionRef = useRef<ActionType>();
  const [row, setRow] = useState<API.ActivityType>();
  const [selectedRowsState, setSelectedRows] = useState<API.ActivityType[]>([]);
  const columns: ProColumns<API.ActivityType>[] = [
    {
      title: '活动封面图',
      dataIndex: 'rPicture',
      hideInSearch: true,
      width: 70,
      render: (_, record) => (
        <>
          <img src={record.rPicture} width="70" alt="活动封面图" />
        </>
      )
    },
    {
      title: '活动号',
      hideInSearch: true,
      hideInForm: true,
      width: 50,
      dataIndex: 'rId',
      tip: '活动号是唯一的 key',
    },
    {
      title: '活动名称',
      dataIndex: 'rName',
      width: 90,
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '活动负责人',
      hideInSearch: true,
      width: 50,
      dataIndex: 'rT',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
      render: (_, record) => (
        <span>{record.rT?.tName}</span>
      )
    },
    {
      title: '活动地址',
      hideInSearch: true,
      width: 80,
      dataIndex: 'rAddressBody',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
      render: (_, record) => (
        <span>{record.rAddressBody?.name}</span>
      )
    },
    {
      title: '举办日期',
      hideInSearch: true,
      width: 70,
      sorter: true,
      dataIndex: 'rStarttime',
      valueType: 'dateTime',
      render: (_, record) => (
        <span>{dateFormat(record.rStarttime)}</span>
      )
    },
    {
      title: '操作',
      width: 160,
      hideInSearch: true,
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => (
        <>
          <Button type='primary'>推送</Button>
          <Divider type="vertical" />
          <Button type='primary'>轮播</Button>
          <Divider type="vertical" />
          <Button type='primary'>评分</Button>
          <Divider type="vertical" />
          <Button type='primary'>名单</Button>
          <Divider type="vertical" />
          <Button type='primary'
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            修改
          </Button>
          <br />
          <br />
          <Button type='primary'>补签</Button>
          <Divider type="vertical" />
          <Button type='primary'>推荐</Button>
          <Divider type="vertical" />
          <Button type='primary'>成绩</Button>
          <Divider type="vertical" />
          <Button type='primary'>详情</Button>
          <Divider type="vertical" />
          <Button type='primary' danger onClick={() => removeById(record.rId)}>删除</Button>
        </>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '首页',
      }}
    >
      <ProTable<API.ActivityType>
        headerTitle="所有活动"
        actionRef={actionRef}
        scroll={{ x: 1650 }}
        rowKey="rId"
        search={{
          labelWidth: 120,
        }}
        request={queryList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            danger
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <ModalCard
          onCancel={() => {
            handleUpdateModalVisible(false)
            setStepFormValues({})
          }}
          modalVisible={updateModalVisible}
        >
          <ProTable<API.ActivityType, API.ActivityType>
            form={{ initialValues: stepFormValues }}
            onSubmit={async (value) => {
              const success = await handleUpdate(value);
              if (success) {
                handleUpdateModalVisible(false);
                setStepFormValues({})
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            rowKey="rId"
            type="form"
            columns={columns}
          />
        </ModalCard>
      ) : null}

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.rId && (
          <ProDescriptions<API.ActivityType>
            column={2}
            title={row?.rId}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.rId,
            }}
            columns={columns as ProDescriptionsItemProps<API.ActivityType>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default HomePage;
